package com.megvii.corelib.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import butterknife.ButterKnife;

/**
 * Created by linyue on 15/12/23.
 */
public abstract class MegviiAdapter<T> extends BaseAdapter
{
    protected Context context;

    protected int layoutId;

    protected Class<T> viewHolderClass;

    protected LayoutInflater inflater;

    private T holder;

    public MegviiAdapter(Context context, Class<T> viewHolderClass)
    {
        this.context = context;
        this.viewHolderClass = viewHolderClass;
        this.inflater = LayoutInflater.from(context);
    }

    /**
     * viewHolderClass必须有public的默认构造函数
     * 如果viewHolderClass是一个内部类，则必须是public static的！
     *
     * @param context
     * @param viewHolderClass
     * @param layoutId
     */
    public MegviiAdapter(Context context, Class<T> viewHolderClass, int layoutId)
    {
        this(context, viewHolderClass);
        this.layoutId = layoutId;
    }

    public void setLayoutId(int layoutId)
    {
        this.layoutId = layoutId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        if (convertView == null)
        {
            try
            {
                convertView = inflater.inflate(layoutId, null);
                holder = viewHolderClass.newInstance();
                ButterKnife.bind(holder, convertView);
                convertView.setTag(holder);
            }
            catch (InstantiationException e)
            {
                e.printStackTrace();
            }
            catch (IllegalAccessException e)
            {
                e.printStackTrace();
            }
        }
        else
        {
            holder = (T) convertView.getTag();
        }
        processViewHolder(holder, position);
        return convertView;
    }

    protected abstract void processViewHolder(T viewHolder, int position);
}
